<?php

namespace Inhoud\Model;

class Index {
    private $_idInhoud = 0;
    private $_controller = null;
    
    public function __construct($controller) {
        $this->_controller = $controller;
    }
    
    public function toegang() {
        $id = \Verzoek::GETPADITEM('id');
        $dbSql = "SELECT * FROM inhoud WHERE publiek=1 AND id=:id";
        try {
            $dbStmt = \Db::GET()->prepare($dbSql);
            $dbStmt->execute([':id'=>$id]);
            if ($dbStmt->rowCount() == 0) {
                return false;
            } else {
                $inhoud = $dbStmt->fetch(\PDO::FETCH_ASSOC);
                $this->_idInhoud = $inhoud['id'];
                return $inhoud;
            }
        } catch (PDOException $ex) {

        }
    }
    
    public function inhoud() {
        $dbSql = "SELECT ic.id, c.klasse
                  FROM inhoudcontainer ic JOIN container c
                  ON ic.idcontainer = c.id
                  WHERE ic.idinhoud=:idinhoud
                  ORDER BY ic.volgnummer";
        try {
            $dbStmt = \Db::GET()->prepare($dbSql);
            $dbStmt->execute([':idinhoud'=>$this->_idInhoud]);
            $resultaat = [];
            while($dbRij = $dbStmt->fetch(\PDO::FETCH_ASSOC)) {
                array_push($resultaat,[$dbRij['klasse'],$this->_moduleInhoud($dbRij['id'])]);
            }
            return $resultaat;
        } catch (PDOException $ex) {

        }
    }
    
    private function _moduleInhoud($id=0) {
        if ($id > 0) {
            $dbSql = "SELECT m.pad, mic.id
                      FROM modules m JOIN moduleinhoudcontainer mic
                      ON mic.idmodule = m.id
                      WHERE mic.idinhoudcontainer = :idinhoud
                      ORDER BY mic.volgnummer";
            try {
                $dbStmt = \Db::GET()->prepare($dbSql);
                $dbStmt->execute([':idinhoud'=>$this->_idInhoud]); 
                
                $return = '';
                while($dbRij = $dbStmt->fetch(\PDO::FETCH_ASSOC)) {
                    $module = new $dbRij['pad']();
                    $return .= $module->index($dbRij['id']);
                }
                return $return;
            } catch (PDOException $ex) {

            }
            
        }
    }
    
    
}
